//
//  ICContactsViewController.m
//  ICome
//
//  Created by ENN on 16/2/17.
//  Copyright © 2016年 XianZhuangGuo. All rights reserved.
//

#import "ICContactsViewController.h"
#import "ICContactsGroup.h"
#import "ICContactItem.h"
#import "ICContactListCell.h"
#import "ICOrganizationViewController.h"
#import "ICPullComboBoxView.h"
#import "ICComboxItem.h"
#import "ICCommonGroup.h"
#import "ICRobotListViewController.h"
#import "ICRobotDetailViewController.h"
#import "ICRobotModel.h"
#import "ICSearchButton.h"
#import "ICContactsSearchController.h"
#import "iComeApiManager.h"

@interface ICContactsViewController ()<UITableViewDataSource, UITableViewDelegate, ICPullComboBoxDelegate>

@property (nonatomic, strong)NSMutableArray *dataList;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)ICPullComboBoxView *boxView;
@property (nonatomic, strong)UIView *tableHearView;

@end

@implementation ICContactsViewController

#pragma mark - life cycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateContacts];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNav];
    [self initNotificationCenter];

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ICContactsGroup *group = [self.dataList objectAtIndex:section];
    return group.items.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.0f * Level;
}

// 设置section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else if (section == 1) {
        return 25;
    }
    return 8.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    if (section == 1) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 25)];
        titleLabel.text = @"常用联系人";
        titleLabel.font = ICFont(14);
        titleLabel.textColor = ICTEXTCOLOR_T2;
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 25)];
        [sectionView addSubview:titleLabel];
        sectionView.backgroundColor = ICRGB(0xefefef);
        return sectionView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ICContactListCell";
    ICContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICContactListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    ICContactsGroup *group = [self.dataList objectAtIndex:indexPath.section];
    cell.item = [group.items objectAtIndex:indexPath.row];
    if (indexPath.row == group.items.count - 1) {
        cell.bottomLineStyle = CellLineStyleFill;
    } else {
        cell.bottomLineStyle = CellLineStyleDefault;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ICCommonGroup *group = [self.dataList objectAtIndex:indexPath.section];
    ICContactItem *item = [group.items objectAtIndex:indexPath.row];
    if(indexPath.section == 1){
        
        NSDictionary *param = @{@"eId":item.eId};
        if ([item.eId rangeOfString:@"bot"].location == NSNotFound) {
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
            } else {
                UIViewController * vc = [[IComMediator sharedInstance] IComMediator_ContactsDetailViewController:param];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else
        {
            UIViewController *vc = [[IComMediator sharedInstance] IComMediator_RobotDetailViewController:param];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        if (item.option) {
            item.option();
            return;
        }
    }
}

#pragma mark - CustomDelegate
- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ICCommonGroup *group = [self.boxView.dataList objectAtIndex:indexPath.section];
    ICCommonItem *model = [group.items objectAtIndex:indexPath.row];
    if (model.destVcClass) {
        ICBaseViewController *vc = [[model.destVcClass alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        if (model.option) {
            model.option();
        }
    }
}

#pragma mark - event response
- (void)rightButtonAction:(UIButton *)sender {
    [self.boxView viewTap];
}

- (void)leftButtonAction:(UIButton *)sender {

}

#pragma mark - private methods
- (BOOL)push:(NSDictionary *)param {
    [super push:param];
    if ([param[@"class"] isEqualToString:@"ad"]) {
        return YES;
    }
    return NO;
}

- (void)setUI
{
    UIView *bView = [[UIView alloc] initWithFrame:self.tableView.frame];
    bView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundView = bView;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

- (void)setNav
{
    self.title = @"通讯录";//@"通讯录";
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"App_menubox_blue" itemType:UIBarButtonItemTypeRight target:self action:@selector(rightButtonAction:)];
}

- (void)reloadDataWithContacts:(NSArray *)contacts {
    [self addGeneralItem];
    if (contacts.count >0) {
        [self addContacts:contacts];
    }
    [self.tableView reloadData];
}

- (void)addGeneralItem {
    [_dataList removeAllObjects];
    WEAKSELF
    ICContactItem *department = [ICContactItem itemWithIcon:@"icon_my_department" title:@"我的部门" destVcClass:[ICOrganizationViewController class]];
    department.option = ^{
        ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];

        //vc.titleName = NSLocalizedString(@"myDepartment", nil);
        vc.CtrStyle = CtrStyleDepart_sdk;
   

        vc.eId = [ICUser currentUser].eId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    ICContactItem *organization = [ICContactItem itemWithIcon:@"icon_organization" title:@"新奥" destVcClass:[ICOrganizationViewController class]];
    organization.option = ^{
        ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
        vc.titleName = @"新奥";
        vc.CtrStyle = CtrStyleDefault_sdk;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    ICContactItem *stranger = [ICContactItem itemWithIcon:@"icon_stranger" title:@"伙伴" destVcClass:[ICOrganizationViewController class]];
    stranger.option = ^{
        
//        [MBProgressHUD showSuccess:@"敬请期待..."];
    };
    
//    ICContactItem *team = [ICContactItem itemWithIcon:@"icon_team" title:NSLocalizedString(@"team", nil) destVcClass:[ICOrganizationViewController class]];
//    team.option = ^{
//        ICTeamViewController *vc = [[ICTeamViewController alloc] init];
//        vc.titleName = NSLocalizedString(@"team", nil);
//        vc.CtrStyle = CtrStyleTeamWork;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
//    };
    ICContactItem *myGroup = [ICContactItem itemWithIcon:@"icon_collaboration" title:@"我的群组" destVcClass:nil];
    myGroup.option = ^{
       
    };
    
    ICContactItem *robot = [ICContactItem itemWithIcon:@"icon_myrobot" title:@"机器人" destVcClass:[ICOrganizationViewController class]];
    robot.option = ^{
//        ICTeamViewController *vc = [[ICTeamViewController alloc] init];
//        vc.titleName = NSLocalizedString(@"myrobot", nil);
//        vc.CtrStyle = CtrStyleTeamWork;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
        ICRobotListViewController *robotListViewController = [[ICRobotListViewController alloc] init];
        [self.navigationController pushViewController:robotListViewController animated:YES];
    };
    
    ICContactsGroup *baseGroup = [[ICContactsGroup alloc] init];
//    baseGroup.items = @[department,organization,myGroup, robot];
    baseGroup.items = @[department,organization];
    
    [_dataList addObject:baseGroup];
}

// 刷新联系人数据
- (void)addContacts:(NSArray *)contacts {
    ICContactsGroup *contactsGroup = [[ICContactsGroup alloc] init];
    NSMutableArray *groupList = [[NSMutableArray alloc] init];
    for (ICUser *model in contacts) {
        NSString *URL = [ICTools getMinImageURL:(model.photoId)];
        ICContactItem *item = [ICContactItem itemWithIcon:URL title:model.eName destVcClass:nil];
        item.eId = model.eId;
//        if ([item.eId rangeOfString:@"bot"].location == NSNotFound) {
//            [groupList addObject:item];
//        }
        [groupList addObject:item];
    }
    contactsGroup.items = [groupList copy];
    [self.dataList addObject:contactsGroup];
}

- (void)initNotificationCenter {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interfaceReloadData:) name:NotificationChangeUIView object:nil];
}

- (void)interfaceReloadData:(NSNotification *)notification {
    [self.tableView reloadData];
}

- (void)updateContacts {
    [ICMessageDatabase recentContactUsers:^(NSArray *array, NSError *error) {
        [self reloadDataWithContacts:array];
    }];
}

- (void)searchAction:(UIButton *)sender {
    ICContactsSearchController *vc = [[ICContactsSearchController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - getters and setters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        [_tableView setSectionIndexColor:ICTEXTCOLOR_T1];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.tableHearView;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(UIView *)tableHearView
{
    if(!_tableHearView)
    {
        _tableHearView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.view.width, 44)];
        _tableHearView.backgroundColor = BACKGROUNDCOLOR;//BACKGROUNDCOLOR;
        ICSearchButton *searchButton = [[ICSearchButton alloc] initWithFrame:CGRectMake(10, 8, App_Frame_Width - 20, 28)];
        searchButton.layer.cornerRadius = 5;
        [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
        searchButton.layer.backgroundColor = [UIColor whiteColor].CGColor;
        [searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
        [_tableHearView addSubview:searchButton];
    }
    return _tableHearView;
}

-(ICPullComboBoxView *)boxView
{
    if (!_boxView)
    {
        ICComboxItem *creatEmpGroup = [ICComboxItem itemWithIcon:@"icon_peoples_session" title:@"多人会话" destVcClass:nil parameter:nil];
        creatEmpGroup.option = ^{
            ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
            vc.titleName = @"多人会话";
            vc.eId = [ICUser currentUser].eId;
            vc.CtrStyle = CtrStyleEmploye_sdk;
            vc.kkGroupType = GroupStyleCreateEmployee;
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        ICComboxItem *creatGroup = [ICComboxItem itemWithIcon:@"icon_department_session" title:@"团队会话" destVcClass:nil parameter:nil];
        creatGroup.option = ^{
            ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
            vc.titleName = @"团队会话";
            vc.eId = [ICUser currentUser].eId;
            vc.CtrStyle = CtrStyleEmploye_sdk;
            vc.kkGroupType = GroupStyleCreateNode;
            [self.navigationController pushViewController:vc animated:YES];
        };
        ICComboxItem *scan = [ICComboxItem itemWithIcon:@"icon_mine_scan" title:@"扫一扫" destVcClass:nil parameter:nil];
        WEAKSELF
        scan.option = ^{
            [ICSystemTool checkCameraAuthorizationStatus:^{
                UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RCodeViewController:nil handler:^(id result) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf pushCustomViewControllerURL:result[@"url"] fromViewController:weakSelf animated:YES];
                    });
                }];
                [weakSelf.navigationController pushViewController:viewController animated:YES];
//                ICNavigationController *nvc = [[ICNavigationController alloc] initWithRootViewController:viewController];
//                [weakSelf presentViewController:nvc animated:YES completion:nil];
            }];
        };
        
        ICComboxItem *setting = [ICComboxItem itemWithIcon:@"icon_contacts_setting" title:@"设置" destVcClass:nil parameter:nil];
        ICCommonGroup *baseGroup = [[ICCommonGroup alloc] init];
        baseGroup.items = @[creatEmpGroup, creatGroup, scan, setting];
        
        _boxView = [[ICPullComboBoxView alloc] initWithFrame:CGRectMake(0, ([ICTools getStatusbarHeight] + [ICTools getNavbarHeight]), App_Frame_Width, APP_Frame_Height)];
        [_boxView.dataList addObject:baseGroup];
        [_boxView.tableView reloadData];
        _boxView.delegate = self;
        [self.view.window addSubview:_boxView];
    }
    return _boxView;
}

- (NSMutableArray *)dataList
{
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
        [self addGeneralItem];
    }
    return _dataList;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
